package org.nowcoder.leetcode.linkedList;

/**
 * Title  : 2. Add Two Numbers
 * Source : https://leetcode.cn/problems/add-two-numbers/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-12
 */

public class LeetCode_2 {
    class ListNode {
        public int val;
        public ListNode next;

        public ListNode() {
        }

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //方法一: 模拟列算术式
        ListNode head = null, p = null;
        int bit = 0, sum;
        while (l1 != null && l2 != null) {
            sum = l1.val + l2.val + bit;
            bit = sum / 10;
            ListNode node = new ListNode(sum % 10);
            if (head == null) {
                head = node;
            } else {
                p.next = node;
            }
            p = node;
            l1 = l1.next;
            l2 = l2.next;
        }
        //处理链表长度不一致情况
        ListNode l = l1;
        if (l == null)
            l = l2;

        while (l != null) {
            sum = l.val + bit;
            bit = sum / 10;
            ListNode node = new ListNode(sum % 10);
            assert p != null;
            p.next = node;
            p = node;
            l = l.next;
        }

        //如果最后一位求和后，还有进位
        if (bit != 0) {
            ListNode node = new ListNode(1);
            p.next = node;
        }
        return head;
    }
}
